//
//  testViewController.swift
//  SSSegmentedViewExample
//
//  Created by xiaobei on 2017/8/23.
//  Copyright © 2017年 xiaobei. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyUserDefaults

class testViewController: BaseViewController,UIImagePickerControllerDelegate {
    let imagePicker = UIImagePickerController()
    var sourceType = UIImagePickerControllerSourceType.camera
    var backImageView = UIImageView()
    let backView = UIView()
    var isIOS : Bool!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.makeBaseUI()
        self.layoutNav()
    }
    func layoutNav(){
        self.view.backgroundColor = UIColor.clear
    }
    func makeBaseUI(){
        
        backView.frame = CGRect(x: 37.5 * _kScreenWidth, y: 20, width: 300 * _kScreenWidth, height: 470 * _kScreenWidth)
        backView.backgroundColor = UIColor.white
        self.view.addSubview(backView)
        
        
        backImageView.frame = CGRect(x: 15 * _kScreenWidth, y: 15, width: 300 * _kScreenWidth - 30, height: 350 * _kScreenWidth)
        backImageView.image = UIImage.init(named: "1111组 1@2x")
        backView.addSubview(backImageView)
        
        
        let codeImage1 = UIImageView()
        backView.addSubview(codeImage1)
        codeImage1.snp.makeConstraints { (make) in
            make.top.equalTo(backImageView.snp.bottom).offset(15)
            make.left.equalTo(backView).offset(15)
            make.size.equalTo(CGSize(width: 66*_kScreenWidth, height: 66*_kScreenWidth))
        }
        let url1 : String!
        if isIOS==true{
            url1 = "https://www.pgyer.com/NErM"
        }else{
            url1 = "http://renedescartes.io/dke.apk";
        }
        //你的头像（可以为nil）
        let headerImage1 = UIImage(named: "")
        //生成图片并且显示
        codeImage1.image = setupQRCodeImage(url1, image: headerImage1)
        
        let iconImageView = UIImageView()
        backView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { (make) in
            make.top.equalTo(backImageView.snp.bottom).offset(15)
            make.left.equalTo(codeImage1.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 43*_kScreenWidth, height: 43*_kScreenWidth))
        }
        iconImageView.image = UIImage.init(named: "11矢量智能对象@2x")
        
        let bottomLabel = UILabel()
        backView.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconImageView.snp.bottom).offset(0)
            make.left.equalTo(codeImage1.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 200*_kScreenWidth, height: 24*_kScreenWidth))
        }
        if isIOS==true{
            bottomLabel.text = XALanguageManager.getString(key: "苹果手机用户长按扫码下载")
        }else{
            bottomLabel.text = XALanguageManager.getString(key: "安卓手机用户长按扫码下载")
        }
        
        bottomLabel.font = UIFont.systemFont(ofSize: 12)
        
        
        let topLabel = UILabel()
        backView.addSubview(topLabel)
        topLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconImageView).offset(0)
            make.left.equalTo(iconImageView.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 200*_kScreenWidth, height: 12*_kScreenWidth))
        }
        topLabel.text = XALanguageManager.getString(key: "我的邀请码")
        topLabel.textColor = UIColor("909090")
        topLabel.font = UIFont.systemFont(ofSize: 10)
        
        let centerLabel = UILabel()
        backView.addSubview(centerLabel)
        centerLabel.snp.makeConstraints { (make) in
            make.top.equalTo(topLabel.snp.bottom).offset(0)
            make.left.equalTo(iconImageView.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 121*_kScreenWidth, height: 43*_kScreenWidth - 12))
        }
        
        centerLabel.text = Defaults[.vip_code]
        centerLabel.font = UIFont.boldSystemFont(ofSize: 20)
        centerLabel.textColor = UIColor("#217AFF")
        centerLabel.adjustsFontSizeToFitWidth = true
        //centerLabel.font = UIFont.systemFont(ofSize: 10)
        var myheight = 64 as CGFloat
        if UIDevice.current.isX(){
            myheight = 104
        }
        
        let bottomBtn = UIButton()
        self.view.addSubview(bottomBtn)
        bottomBtn.frame = CGRect(x:kScreenW/2 - 60, y: kScreenH - 40 - myheight - 50, width: 120, height: 33)
        bottomBtn.setTitle(XALanguageManager.getString(key: "保存到相册"), for: .normal)
        bottomBtn.layer.cornerRadius = 16.5
        bottomBtn.addTarget(self, action: #selector(self.baoCunAction), for: .touchUpInside)
        bottomBtn.backgroundColor = UIColor("#217AFF")
        
        let chengeBtn = UIButton()
        self.view.addSubview(chengeBtn)
        chengeBtn.backgroundColor = UIColor("#000000")
        chengeBtn.alpha = 0.5
        chengeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(backView.snp.top).offset(30)
            make.right.equalTo(backView).offset(-15)
            make.size.equalTo(CGSize(width: 60, height: 20))
        }
        chengeBtn.setTitle(XALanguageManager.getString(key: "更换"), for: .normal)
        chengeBtn.layer.cornerRadius = 10
        chengeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        chengeBtn.addTarget(self, action: #selector(testViewController.buttonAction), for: .touchUpInside)
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePicker.delegate = self
            //imagePicker.allowsEditing = true
        }
        
        
    }
    
    @objc func buttonAction() {
        let alertVc = UIAlertController.init(title: XALanguageManager.getString(key: "选择照片"), message: "", preferredStyle: .actionSheet)
        let takeAction = UIAlertAction.init(title: XALanguageManager.getString(key: "拍照"), style: .default) { (model) in
            self.takePhoto()
        }
        let chooseAction = UIAlertAction.init(title: XALanguageManager.getString(key: "从相册选择"), style: .default) { (model) in
            self.choosePhoto()
        }
        let cancelAction = UIAlertAction.init(title: XALanguageManager.getString(key: "取消"), style: .cancel) { (model) in
            
        }
        alertVc.addAction(takeAction)
        alertVc.addAction(chooseAction)
        alertVc.addAction(cancelAction)
        self.present(alertVc, animated: true, completion: nil)
    }
    
    private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //myImages.append(pickedImage)
        }
        imagePicker.dismiss(animated:true, completion: nil)
        
        //dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func takePhoto(){
        sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.sourceType = sourceType
        self.present(imagePicker, animated: true, completion: nil)
        
    }
    
    @objc func choosePhoto(){
        sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.sourceType = sourceType
        self.present(imagePicker, animated: true, completion: nil)
    }
    
    
    
    @objc func baoCunAction(){
        UIImageWriteToSavedPhotosAlbum(testViewController.getImageFromView(view: backView), self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    
    
    @objc func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        print("---")
        
        // if didFinishSavingWithError != nil {
        if error != nil {
        SVProgressHUD.showError(withStatus: "保存失败")
            return
        }
        SVProgressHUD.showSuccess(withStatus: XALanguageManager.getString(key: "Preservation Success"))
    }
    
    
   
    //    将某个view 转换成图像
    class func getImageFromView(view:UIView) ->UIImage{
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 300 * _kScreenWidth, height: 470 * _kScreenWidth), false, 0.0);
        //view.layer.render(in: UIGraphicsGetCurrentContext as! CGContext)
        
     
        
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
        
    }
    
    
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 width: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }

}
extension testViewController :  UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.backImageView.image = pickedImage
        }
    }
}
